#!/bin/bash
#ROOT是变量，在安装的时候会被替换
db=ROOT/db

iptables -t filter -P INPUT DROP
iptables -t filter -P OUTPUT ACCEPT
iptables -t filter -P FORWARD ACCEPT
iptables -t filter -F

iptables -t filter -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -t filter -A INPUT -i lo -j ACCEPT

sqlite3 "$db" "delete from portConfig;"
#执行plugin目录下的所有脚本
for s in $(ls ROOT/plugin/*);do
    echo "plugin: $s"
    if file $s | grep -q 'shell script';then
        bash "$s"
    fi
done
#从portConfig数据表中读取
enabledPorts=$(sqlite3 "$db" "select type,port from portConfig where enabled=1;")
#debug
echo "enabledPorts: $enabledPorts"

if [ -n "$enabledPorts" ];then
    echo "$enabledPorts" | while read record;do
        type=$(echo $record | awk -F'|' '{print $1}')
        port=$(echo $record | awk -F'|' '{print $2}')
        #debug
        echo "start-iptables:"
        echo "type: $type"
        echo "port: $port"
        if ! iptables -nL INPUT | grep $type | grep -q ":$port";then
            echo "execute iptables -t filter -A INPUT -p $type -m $type --dport $port -j ACCEPT"
            cmd="iptables -t filter -A INPUT -p $type -m $type --dport $port -j ACCEPT"
            bash -c "$outputcmd"
        fi
        #为了监控从这个端口的输出流量
        if ! iptables -nL OUTPUT | grep $type | grep -q ":$port";then
            echo "execute iptables -t filter -A OUTPUT -p $type --sport $port"
            outputcmd="iptables -t filter -A OUTPUT -p $type --sport $port"
            bash -c "$cmd"
        fi
    done
fi
